﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Drawing;

using DNA;
using TJADRICD.CollaborativeDesignPlugin.Form;
using TJADRICD.CollaborativeDesignPlugin.Function;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.ApplicationServices;
using DBTransMan = Autodesk.AutoCAD.DatabaseServices.TransactionManager;
using Application = Autodesk.AutoCAD.ApplicationServices.Application;
using Autodesk.AutoCAD.PlottingServices;
using System.Runtime.InteropServices;
using TJADRICD.CollaborativeDesignPlugin.PreArchive;
namespace TJADRICD.CollaborativeDesignPlugin.Form
{
    public partial class FormCheckSignFiles : System.Windows.Forms.Form
    {
        public FormCheckSignFiles()
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
        }

        struct Pair
        {
            public string fileName;
            public FileStream fs;
            public Pair(string fileName, FileStream fs)
            {
                this.fileName = fileName;
                this.fs = fs;
            }
        }
        List<Pair> locks = new List<Pair>();

        private string GetAttributeByPosition(Database db, Point3d position)
        {
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable table = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                foreach (ObjectId recorfId in table)
                {
                    BlockTableRecord record = trans.GetObject(recorfId, OpenMode.ForRead) as BlockTableRecord;
                    if (CommandFrame.IsVersionType(record.Name))
                    {
                        ObjectIdCollection RefIds = record.GetBlockReferenceIds(true, true);
                        foreach (ObjectId RefId in RefIds)
                        {
                            BlockReference Reference = trans.GetObject(RefId, OpenMode.ForRead) as BlockReference;
                            AttributeCollection RefAttrisId = Reference.AttributeCollection;
                            foreach (ObjectId AttriId in RefAttrisId)
                            {
                                AttributeReference AttriRef = trans.GetObject(AttriId, OpenMode.ForRead) as AttributeReference;
                                if (AttriRef.Tag.EndsWith("SignPos") && (AttriRef.Position == position))
                                {
                                    return AttriRef.Tag.Substring(0, AttriRef.Tag.Length - "SignPos".Length);
                                }
                            }
                        }
                    }
                }
                return "";
            }
        }

        private void FormCheckSignFiles_Load(object sender, EventArgs e)
        {
            foreach (string webPath in Config.ProjectPath)
            {
                DirectoryInfo Dir_Web = new DirectoryInfo(webPath);
                DirectoryInfo[] Dir_Pros = Dir_Web.GetDirectories();
                foreach (DirectoryInfo Dir_Pro in Dir_Pros)
                {
                    if ((Dir_Pro.Name == "Sign") || (Dir_Pro.Name == "TK"))
                    {
                        continue;
                    }
                    this.cb_ProNo.Items.Add(Dir_Pro.Name);
                }
            }
        }

        private void btnAddFile_Click(object sender, EventArgs e)
        {
            if (this.cb_SubProNo.Text != "")
            {
                OpenFileDialog ofd = new OpenFileDialog();
                string dir = CommandSign.makeSubProDir(this.cb_ProNo.Text, this.cb_SubProNo.Text, this.cb_Major.Text);
                if (!(new DirectoryInfo(dir)).Exists)
                {
                    MessageBox.Show("目录不存在!");
                    return;
                }
                ofd.InitialDirectory = dir;
                ofd.Filter = "Dwawing(*.dwg)|*.dwg";
                ofd.Multiselect = true;
                DialogResult dr = ofd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                    int count = 0;
                    foreach (string file in ofd.FileNames)
                    {
                        ++count;
                    }
                    this.progressBar1.Visible = true;
                    this.progressBar1.Maximum = count;
                    count = 0;
                    foreach (string file in ofd.FileNames)
                    {
                        AddFile(file);
                        LockFile(file);
                        this.progressBar1.Increment(++count);
                    }
                    this.Cursor = System.Windows.Forms.Cursors.Default;
                    MessageBox.Show("导入完成!");
                    this.progressBar1.Visible = false;
                }
            }
        }

        private void btnAddFiles_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.cb_SubProNo.Text != "")
                {
                    this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                    string rootFolderPath = CommandSign.makeSubProDir(this.cb_ProNo.Text, this.cb_SubProNo.Text, this.cb_Major.Text);
                    if (!(new DirectoryInfo(rootFolderPath)).Exists)
                    {
                        MessageBox.Show("目录不存在!");
                        this.Cursor = System.Windows.Forms.Cursors.Arrow;
                        return;
                    }
                    List<string> files = new List<string>();
                    CommandSign.GoThroughDirectory(rootFolderPath, ref files);
                    int count = 0;
                    foreach (string fileName in files)
                    {
                        if (Path.GetExtension(fileName) == ".dwg")
                        {
                            ++count;
                        }
                    }
                    this.progressBar1.Visible = true;
                    this.progressBar1.Maximum = count;
                    count = 0;
                    foreach (string fileName in files)
                    {
                        if (Path.GetExtension(fileName) == ".dwg")
                        {
                            AddFile(fileName);
                            LockFile(fileName);
                            this.progressBar1.Increment(++count);
                        }
                    }
                    MessageBox.Show("导入完成!");
                    this.progressBar1.Visible = false;
                    this.Cursor = System.Windows.Forms.Cursors.Default;
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        /// <summary>
        /// 加锁
        /// </summary>
        /// <param name="fileName"></param>
        private void LockFile(string fileName)
        {
        }
        /// <summary>
        /// 解锁
        /// </summary>
        /// <param name="fileName"></param>
        private void UnLockFile(string fileName)
        {
        }

        /// <summary>
        /// 解锁所有文件
        /// </summary>
        private void UnLockAllFiles()
        {
            for (int i = 0; i < dataGridView.Rows.Count; i++)
            {
                UnLockFile(dataGridView.Rows[i].Cells["FileName"].Value.ToString());
            }
        }

        /// <summary>
        /// 在datagridview控件里加入文件
        /// </summary>
        /// <param name="fileName"></param>
        public void AddFile(string fileName)
        {
            try
            {
                Editor ed = Tools.Editor;
                //如果已经添加过此文件，无视
                foreach (DataGridViewRow row in dataGridView.Rows)
                {
                    string oldFileName = row.Cells["FileName"].Value.ToString();
                    if (oldFileName == fileName)
                    {
                        //                        MessageBox.Show(oldFileName + "已添加过，跳过！");
                        return;
                    }
                    int oldLength = oldFileName.Length;
                    int newLength = fileName.Length;
                    if (oldFileName.Substring(0, oldLength - 5) == fileName.Substring(0, newLength - 5))
                    {
                        if (oldFileName[oldLength - 5] >= fileName[newLength - 5])
                        {
                            //                        MessageBox.Show(fileName + "版本过低，跳过");
                            return;
                        }
                        if (oldFileName[oldLength - 5] < fileName[newLength - 5])
                        {
                            UnLockFile(row.Cells["FileName"].Value.ToString());
                            dataGridView.Rows.Remove(row);
                            break;
                        }
                    }
                }

                if (cb_AutoSign.Checked)
                {
                    string temp = "";
                    for (int iCount = fileName.Length - 1; iCount >= 0; --iCount)
                    {
                        if (fileName[iCount] == '\\')
                        {
                            temp = fileName.Substring(0, iCount + 1);
                            CommandSign.QuickSign(temp);
                            break;
                        }
                    }
                }

                //对于此文件，找到其中的图框并加入
                using (Database db = new Database(false, true))
                {
                    db.ReadDwgFile(fileName,
                        FileShare.ReadWrite,
                        false,
                        "");

                    string strDbHashCode = Function_Hash.GetDwgHash(db);

                    //Tools.WriteMessageWithReturn("全局Hash值:" + strDbHashCode);

                    using (Transaction trans = db.TransactionManager.StartTransaction())
                    {
                        BlockTable table = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite);
                        BlockTableRecord btr = trans.GetObject(table[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                        //先找到所有的签名块，取得它们的位置，方便后面检索哪些栏目已经被签过了
                        List<List<Point3d>> possList = new List<List<Point3d>>();
                        List<string> names = new List<string>();
                        List<Point3d> otherposs = new List<Point3d>();//其他人员签名位置
                        List<string> unsignItems = new List<string>();
                        BlockReference brFrame = null;
                        foreach (ObjectId blockId in table)
                        {
                            BlockTableRecord record = (BlockTableRecord)trans.GetObject(blockId, OpenMode.ForWrite);
                            if (CommandFrame.IsVersionType(record.Name))
                            {
                                ObjectIdCollection collection = record.GetBlockReferenceIds(true, true);
                                foreach (ObjectId frameId in collection)
                                {
                                    brFrame = trans.GetObject(frameId, OpenMode.ForWrite) as BlockReference;
                                    break;
                                }
                            }
                        }
                        if (brFrame == null)
                        {
                            return;
                        }
                        if (brFrame.ExtensionDictionary == ObjectId.Null)
                        {
                            Tools.WriteMessageWithReturn("No Dictionary!");
                        }
                        else
                        {
                            DBDictionary dictionary = trans.GetObject(brFrame.ExtensionDictionary, OpenMode.ForRead) as DBDictionary;
                            AttributeCollection ac = brFrame.AttributeCollection;
                            foreach (ObjectId attrId in ac)
                            {
                                AttributeReference signAr = trans.GetObject(attrId, OpenMode.ForWrite) as AttributeReference;
                                if (signAr.Tag.EndsWith("SignPos"))
                                {
                                    string signItem = signAr.Tag.Substring(0, signAr.Tag.Length - "SignPos".Length);
                                    if (!dictionary.Contains(signItem))
                                    {

                                        continue;
                                    }
                                    ObjectId xRecId = dictionary.GetAt(signItem);
                                    Xrecord xRec = trans.GetObject(xRecId, OpenMode.ForRead) as Xrecord;
                                    ResultBuffer data = xRec.Data;
                                    bool flag1 = false, flag2 = false;
                                    string singleMd5 = Function_Hash.GetSingleMD5String(brFrame);
                                    foreach (TypedValue tv in data)
                                    {
                                        if (tv.Value.ToString() == singleMd5)
                                        {
                                            flag1 = true;
                                        }
                                        if (tv.Value.ToString() == strDbHashCode)
                                        {
                                            flag2 = true;
                                        }
                                    }
                                    if (flag1 && flag2)
                                    {
                                        string name = signAr.TextString;
                                        if (name == "hand")
                                        {
                                            foreach (ObjectId idtemp in ac)
                                            {
                                                AttributeReference artemp = trans.GetObject(idtemp, OpenMode.ForWrite) as AttributeReference;
                                                if (artemp.Tag == signItem)
                                                {
                                                    name = artemp.TextString;
                                                }
                                            }
                                        }
                                        int id = names.IndexOf(name);
                                        if (id != -1)
                                        {
                                            possList[id].Add(signAr.Position);
                                        }
                                        else
                                        {
                                            names.Add(name);
                                            List<Point3d> poss = new List<Point3d>();
                                            poss.Add(signAr.Position);
                                            possList.Add(poss);
                                        }
                                    }
                                    else
                                    {
                                        Tools.WriteMessageWithReturn("找到过期签名");
                                        unsignItems.Add(signItem);
                                    }
                                }
                            }
                        }
                        TJADRICD.CollaborativeDesignPlugin.CommandSign.UnsignDB(db, unsignItems);
                        db.SaveAs(db.Filename, DwgVersion.Current);

                        foreach (ObjectId blockId in table)
                        {
                            BlockTableRecord record = (BlockTableRecord)trans.GetObject(blockId, OpenMode.ForRead);

                            if (CommandFrame.IsVersionType(record.Name))  //如果此块定义名符合图框块名
                            {
                                ObjectIdCollection blockRefIds = record.GetBlockReferenceIds(true, true);  //取得此块定义所关联的所有块参照Id
                                foreach (ObjectId blockRefId in blockRefIds)
                                {
                                    string sheetTitle = "";
                                    string discipline = "";
                                    string stage = "";
                                    string sheetNo = "";
                                    string rev2 = "";
                                    string ApprovedBy = "";
                                    string ReviewedBy = "";
                                    string CheckedBy = "";
                                    string PrincipalInCharge1 = "";
                                    string PrincipalInCharge2 = "";
                                    string DisciplineResponsible1 = "";
                                    string DisciplineResponsible2 = "";
                                    string DesignedBy1 = "";
                                    string DesignedBy2 = "";
                                    string DrawnBy = "";

                                    BlockReference blockRef = (BlockReference)trans.GetObject(blockRefId, OpenMode.ForRead);
                                    AttributeCollection blockRefAttrs = blockRef.AttributeCollection;
                                    foreach (ObjectId attrRefId in blockRefAttrs)
                                    {
                                        AttributeReference attrRef = (AttributeReference)trans.GetObject(attrRefId, OpenMode.ForWrite);
                                        if (attrRef.Tag == "SheetTitleChinese")
                                        {
                                            sheetTitle = attrRef.TextString;
                                        }
                                        if (attrRef.Tag == "DisciplineChinese")
                                        {
                                            discipline = attrRef.TextString;
                                        }
                                        if (attrRef.Tag == "StageChinese")
                                        {
                                            stage = attrRef.TextString;
                                        }
                                        if (attrRef.Tag == "SheetNo")
                                        {
                                            sheetNo = attrRef.TextString;
                                        }
                                        if (attrRef.Tag == "Rev2")
                                        {
                                            rev2 = attrRef.TextString;
                                        }
                                        #region poss
                                        for (int i = 0; i < possList.Count; i++)
                                        {
                                            foreach (Point3d pos in possList[i])
                                            {
                                                if (attrRef.Position == pos)
                                                {
                                                    if (attrRef.Tag == "ApprovedBySignPos")
                                                    {
                                                        ApprovedBy = names[i];
                                                    }
                                                    if (attrRef.Tag == "ReviewedBySignPos")
                                                    {
                                                        ReviewedBy = names[i];
                                                    }
                                                    if (attrRef.Tag == "CheckedBySignPos")
                                                    {
                                                        CheckedBy = names[i];
                                                    }
                                                    if (attrRef.Tag == "PrincipalInCharge1SignPos")
                                                    {
                                                        PrincipalInCharge1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "PrincipalInCharge2SignPos")
                                                    {
                                                        PrincipalInCharge2 = names[i];
                                                    }
                                                    if (attrRef.Tag == "DisciplineResponsible1SignPos")
                                                    {
                                                        DisciplineResponsible1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "DisciplineResponsible2SignPos")
                                                    {
                                                        DisciplineResponsible2 = names[i];
                                                    }
                                                    if (attrRef.Tag == "DesignedBy1SignPos")
                                                    {
                                                        DesignedBy1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "DesignedBy2SignPos")
                                                    {
                                                        DesignedBy2 = names[i];
                                                    }
                                                    if (attrRef.Tag == "DrawnBySignPos")
                                                    {
                                                        DrawnBy = names[i];
                                                    }
                                                }
                                            }
                                        }
                                        #endregion
                                    }

                                    bool allChecked = false;
                                    if (ApprovedBy != ""
                                        && ReviewedBy != ""
                                        && CheckedBy != ""
                                        && !(PrincipalInCharge1 == "" && PrincipalInCharge2 == "")
                                        && !(DisciplineResponsible1 == "" && DisciplineResponsible2 == "")
                                        && !(DesignedBy1 == "" && DesignedBy2 == "")
                                        && DrawnBy != ""
                                        )
                                        allChecked = true;
                                    dataGridView.Rows.Add(new object[] { false, allChecked, sheetTitle, fileName,
                                                discipline, stage, sheetNo, rev2,
                                                ApprovedBy, ReviewedBy, CheckedBy, PrincipalInCharge1, PrincipalInCharge2, DisciplineResponsible1, DisciplineResponsible2, DesignedBy1, DesignedBy2, DrawnBy });
                                    return; //只需要第一个图框就够了
                                }
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                Tools.WriteMessageWithReturn("由于文件打开冲突，跳过文件：" + fileName);
                Tools.WriteMessageWithReturn(ex.ToString());
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        static public void GeoTest()
        {
            Database db = Tools.Database;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                TextStyleTable tst = trans.GetObject(db.TextStyleTableId, OpenMode.ForRead) as TextStyleTable;
                foreach (ObjectId id in tst)
                {
                    TextStyleTableRecord ts = trans.GetObject(id, OpenMode.ForRead) as TextStyleTableRecord;
                    Tools.WriteMessageWithReturn(ts.Name);
                }
            }
        }

        private void btnExclude_Click(object sender, EventArgs e)
        {
            for (int i = dataGridView.Rows.Count - 1; i >= 0; i--)
            {
                if (dataGridView.Rows[i].Cells["Operation"].FormattedValue.ToString() == "True")
                {
                    UnLockFile(dataGridView.Rows[i].Cells["FileName"].Value.ToString());
                    dataGridView.Rows.RemoveAt(i);
                }
            }
        }

        private void btnPublish_Click(object sender, EventArgs e)
        {
            for (int iCount = 0; iCount < dataGridView.Rows.Count; ++iCount)
            {
                if (dataGridView.Rows[iCount].Cells["AllChecked"].FormattedValue.ToString() == "True")
                {
                    string strFilePath = dataGridView.Rows[iCount].Cells["FileName"].Value.ToString();
                    try
                    {
                        UnLockFile(strFilePath);
                        Database dbToPublish = new Database(false, true);
                        dbToPublish.ReadDwgFile(strFilePath, System.IO.FileShare.ReadWrite, false, "");
                        for (; ; )
                        {
                            if (PlotFactory.ProcessPlotState == ProcessPlotState.NotPlotting)
                            {
                                break;
                            }
                        }
                        Application.DocumentManager.Open(strFilePath);
                        Document doc = Application.DocumentManager.MdiActiveDocument;

                        GeoTest();
                        doc.LockDocument();


                        FileInfo tfi = new FileInfo(doc.Database.Filename);
                        Function.Function_PlotStyle.DownloadPlotStyle(tfi.Name, tfi.Directory.FullName);
                        Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("BACKGROUNDPLOT", Convert.ToInt16(0));
                        Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("IMAGEFRAME", Convert.ToInt16(0));
                        Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("IMAGEFRAME", Convert.ToInt16(1));
                        Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("IMAGEFRAME", Convert.ToInt16(0));
                        
                        try
                        {
                            if (checkBox3.Checked)
                            {
                               Function_Publish.PublishSingle(doc.Database, "DWF6 ePlot.pc3");
                            }
                        }
                        catch (System.Exception ex)
                        {

                            MessageBox.Show("error print dwf"+ex.ToString());
                        }
                        try
                        {
                            Function_Publish.PublishSingle(doc.Database, "DWG To PDF.pc3"/*"ISO_full_bleed_4A0_(1682.00_x_2378.00_MM)"*/);

                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show("error print pdf" + ex.ToString());
                        }
                        try
                        {
                            if (checkBox1.Checked)
                            {
                                Function_Publish.PublishSingle(doc.Database, "DesignJet 700 C4706B.pc3");
                            }
                        }
                        catch (System.Exception ex)
                        {

                            MessageBox.Show("error print plt" + ex.ToString());
                        }
                        Document c = Application.DocumentManager.MdiActiveDocument;
                        c.CloseAndDiscard();
                    }
                    catch (System.Exception ex)
                    {
                        Tools.WriteMessageWithReturn(ex.ToString());
                    }
                }
            }
            //归档
            PreArchiveService preArchiveService=new PreArchiveService();
            string preArchivePath = preArchiveService.getDirectoryPath(cb_ProNo.Text, cb_SubProNo.Text);
            preArchiveService.makeDirectory(preArchivePath);
            preArchiveService.preArchive(PreArchiveConfiguration.testPath, preArchivePath);
            MessageBox.Show("完成！");
            this.Close();
        }

        private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
        }
        private void FormCheckSignFiles_FormClosing(object sender, FormClosingEventArgs e)
        {
            UnLockAllFiles();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string path = "";
                FolderDialog fd = new FolderDialog();
                fd.DisplayDialog();
                path = fd.Path;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cb_ProNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            string fatherpath = "";
            foreach (string webPath in Config.ProjectPath)
            {
                DirectoryInfo Dir_Web = new DirectoryInfo(webPath);
                DirectoryInfo[] Dir_Pros = Dir_Web.GetDirectories();
                foreach (DirectoryInfo Dir_Pro in Dir_Pros)
                {
                    if (Dir_Pro.Name == this.cb_ProNo.Text)
                    {
                        fatherpath = webPath;
                    }
                }
            }
            this.cb_SubProNo.Items.Clear();
            this.cb_SubProNo.Text = "";
            DirectoryInfo Dir_Web2 = new DirectoryInfo(fatherpath + this.cb_ProNo.Text + "\\");
            DirectoryInfo[] Dir_Pros2 = Dir_Web2.GetDirectories();
            foreach (DirectoryInfo Dir_Pro in Dir_Pros2)
            {
                this.cb_SubProNo.Items.Add(Dir_Pro.Name);
            }
        }
        private void cb_SubProNo_SelectedIndexChanged(object sender, EventArgs e)
        {
        }
    }
}